//
//  DateBoxView.swift
//  YouCaiShoppingMall
//
//  Created by 优裁科技 on 2017/11/29.
//  Copyright © 2017年 优裁科技. All rights reserved.
//

import UIKit

/**
 * 日期下拉选择弹框
 */
class DateBoxView: UIView {

    private let content_height:CGFloat = 200
    private let content_head_view_height:CGFloat = 50
    private let animation_interval:TimeInterval = 0.35
    private let list_cell_count = 1
    private let k_window:UIWindow = UIApplication.shared.keyWindow!
    
    /** 当前选中的值 */
    private var current_value:String? {
        get {
            return Utils.shareInstance().getStringDateTimeFor(Date: self.datePicker.date,
                                        strFormat: "yyyy-MM-dd HH:mm:ss")
        }
    }
    
    /** 标题 */
    var boxTitle:String? {
        didSet{
            self.labBoxTitle.text = boxTitle
        }
    }
    
    /// 确定回调(返回当前选中的值/nil)
    var selectBoxFinish:((String?)->())? = nil


    //MARK: - override func
    override init(frame: CGRect) {
        super.init(frame: frame)

        self.backgroundColor = UIColor.clear
        self.initView()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override func updateConstraints() {
        super.updateConstraints()
        
        self.contentView.snp.makeConstraints { make in
            make.left.right.equalTo(0)
            make.height.equalTo(content_height)
            make.bottom.equalTo(-K_APP_SAFETY_HEIGHT)
        }
        
        self.headView.snp.makeConstraints { make in
            make.left.right.equalTo(0)
            make.top.equalTo(0)
            make.height.equalTo(content_head_view_height)
        }
        
        self.btnCancle.snp.makeConstraints { make in
            make.left.top.equalTo(0)
            make.width.equalTo(70)
            make.height.equalTo(content_head_view_height - 1)
        }
        
        self.btnOk.snp.makeConstraints { make in
            make.right.top.equalTo(0)
            make.width.equalTo(70)
            make.height.equalTo(content_head_view_height - 1)
        }
        
        self.datePicker.snp.makeConstraints { make in
            make.left.right.bottom.equalTo(0)
            make.top.equalTo(content_head_view_height)
        }
        
        self.labBoxTitle.snp.makeConstraints {[weak self] make in
            guard let self = self else { return }
            make.width.equalTo(160)
            make.top.bottom.equalTo(0)
            make.centerX.equalTo(self.snp.centerX)
        }
    }
    
    
    //MARK: - initView
    private func initView(){
        //点击手势
        let tap = UITapGestureRecognizer.init(target: self, action: #selector(tapGestureAction))
        self.addGestureRecognizer(tap)
       
        //轻扫事件
        let swipe = UISwipeGestureRecognizer.init(target: self, action: #selector(swipeGestureAction(sender:)))
        swipe.direction = UISwipeGestureRecognizer.Direction.down
        self.addGestureRecognizer(swipe)
        
        self.addSubview(self.contentView)
        self.contentView.addSubview(self.headView)
        self.headView.addSubview(self.btnCancle)
        self.headView.addSubview(self.btnOk)
        self.headView.addSubview(self.labBoxTitle)
        self.contentView.addSubview(self.datePicker)
        
        setNeedsUpdateConstraints()
    }
    
    /** 更新信息
    * @para strValue String   字符串时间
    * @para type Int 时间格式(0：yyyy-MM-dd 1: yyyy/MM/dd)
    */
    func reloadData(strValue:String,type:Int = 0){
        let date = Utils.shareInstance().getDateForStringDate(strDateTime: strValue, convertType: type)

        self.datePicker.date = date!
    }

    
    //MARK: - 按钮点击
    @IBAction private func btnAction(sender:UIButton) {
        if sender == self.btnOk {
            self.selectBoxFinish?(self.current_value)
        }
        else {
            self.selectBoxFinish?(nil)
        }
       
        self.hideBoxView()
    }


    //MARK: - 轻扫手势
    @objc private func swipeGestureAction(sender:UISwipeGestureRecognizer) {
        if sender.direction == .down {
            self.hideBoxView()
            self.selectBoxFinish?(nil)
        }
    }
    
    //MARK: - 点击手势
    @objc private func tapGestureAction(sender:UITapGestureRecognizer) {
        self.hideBoxView()
        self.selectBoxFinish?(nil)
    }

    
    //MARK: - 显示视图
    /** 显示视图 */
    func showBoxView(){

        //关闭当前键盘
        self.endEditing(true)
        UIApplication.shared.keyWindow?.endEditing(true)
        
        if !k_window.subviews.contains(self) {
            k_window.addSubview(self)
            
            self.contentView.y = K_APP_WIDTH
            UIView.animate(withDuration: animation_interval, animations: {
                //self.contentView.alpha = 1
                self.contentView.y = K_APP_HEIGHT - self.content_height - K_APP_SAFETY_HEIGHT
            }) { (finished:Bool) in
                self.layer.backgroundColor = UIColor.init(red: 0, green: 0, blue: 0, alpha: 0.3).cgColor
            }
        }
    }
    
    /** 移除视图 */
    func hideBoxView(){
        
        if k_window.subviews.contains(self) {
            
            UIView.animate(withDuration: animation_interval, animations: {
                self.contentView.y = K_APP_HEIGHT
            }) { (finished:Bool) in
                //self.contentView.alpha = 0

                self.layer.backgroundColor = UIColor.clear.cgColor
                self.removeFromSuperview()
                print("视图已移除")
            }
        }
    }

    
    //MARK: - lazy load
    private lazy var contentView:UIView = {
        let _v = UIView.init()
        _v.backgroundColor = K_APP_CELL_BGCOLOR
        //_v.alpha = 0
        
        return _v
    }()
    
    private lazy var headView:UIView = {
        let _v = UIView.init()
        
        //底部线
        let h:CGFloat = 0.3
        let y = content_head_view_height - h
        let _l = UIView.init(frame: CGRect.init(x: 0, y: y, width: K_APP_WIDTH, height: h))
        _l.backgroundColor = UIColor.init().colorFromHexString(hex: "#E5E5E5")
        _v.addSubview(_l)
        
        return _v
    }()
    
    private lazy var btnCancle:UIButton = {
        let _b = UIButton.init(type: .custom)
        _b.backgroundColor = UIColor.clear
        _b.contentHorizontalAlignment = .center
        
        _b.setTitle("取消", for: .normal)
        _b.setTitleColor(UIColor.gray, for: .normal)
        _b.titleLabel?.font = UIFont.systemFont(ofSize: 16)
        _b.addTarget(self, action: #selector(btnAction(sender:)), for: .touchUpInside)
        
        return _b
    }()
    
    private lazy var btnOk:UIButton = {
        let _b = UIButton.init(type: .custom)
        _b.backgroundColor = UIColor.clear
        _b.contentHorizontalAlignment = .center
        
        _b.setTitle("确定", for: .normal)
        _b.setTitleColor(UIColor.init().colorFromHexString(hex: "#4B72E5"), for: .normal)
        _b.titleLabel?.font = UIFont.systemFont(ofSize: 16)
        _b.addTarget(self, action: #selector(btnAction(sender:)), for: .touchUpInside)
        
        return _b
    }()
    
    lazy var datePicker:UIDatePicker = {
        let _datePicker = UIDatePicker.init()
        
        _datePicker.locale = Locale.init(identifier: "zh_CN")
        _datePicker.datePickerMode = .dateAndTime
        
        _datePicker.backgroundColor = UIColor.clear
        _datePicker.tintColor = UIColor.black
        
        if #available(iOS 13.4, *) {
            _datePicker.preferredDatePickerStyle = .wheels
        } 
        
        return _datePicker
    }()
    
    private lazy var labBoxTitle:YYLabel = {
        let _lab = YYLabel.init()
        _lab.textColor = K_APP_BOXVIEW_TITLE_COLOR
        _lab.textAlignment = .center
        _lab.font = UIFont.boldSystemFont(ofSize: 16)
        
        return _lab
    }()
}
